package com.edu.hre.struts.action.pim;

import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.edu.hre.common.encrypt.Encrypter;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.ComboBoxInit;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreEmpPicture;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.sql.pim.EmployeeDAOService;
import com.edu.hre.struts.form.pim.EmployeeAddForm;
import com.google.gwt.http.client.Response;

public class EmployeeAddAction extends Action {

	private static final Logger logger = Logger.getLogger(EmployeeAddAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private static final EmployeeDAOService employeeDAOService = BeanFinder.getBean(EmployeeDAOService.BEAN_NAME, EmployeeDAOService.class);
	private final String ACTION_NAME = "employeeAdd";
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		
		EmployeeAddForm beanForm = (EmployeeAddForm) form;
		beanForm.setIsAddNew(true);

		if(request.getParameter(StringConstants.BTN_ADD) == null){
			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		String message = validateForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		HreEmployee tmp = new HreEmployee();
		tmp.setEmpFirstname(CommonUtils.normalizeString(beanForm.getEmpFirstname()));
		tmp.setEmpMiddleName(CommonUtils.normalizeString(beanForm.getEmpMiddleName()));
		tmp.setEmpLastname(CommonUtils.normalizeString(beanForm.getEmpLastname()));
		tmp.setEmpIdCardNum(CommonUtils.normalizeString(beanForm.getIdCardNumber()));
		tmp.setDateCreated(new Date());
		tmp.setDateModified(new Date());
		tmp.setIsDeleted(false);

		if (!baseService.saveOrUpdate(tmp)) {
			beanForm.setMessage("The system has failed to add new employee!");
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		FormFile myFile = beanForm.getImage();
		if(myFile != null && StringUtils.isNotBlank(myFile.getFileName())){
			HreEmpPicture picture = new HreEmpPicture();
			picture.setEpicType(myFile.getContentType());
			picture.setEmpNumber(tmp.getEmpNumber());
			picture.setEpicFileSize(String.valueOf(myFile.getFileSize()));
			picture.setDateModified(new Date());
			picture.setDateCreated(new Date());
			picture.setEpicFilename(myFile.getFileName());
			picture.setEpicPicture(myFile.getFileData());
			String w = null;
			String h = null;
			try {
				Image imgTemp = ImageIO.read(new ByteArrayInputStream(myFile.getFileData()));
				w = imgTemp.getWidth(null) + StringConstants.BLANK;
				h = imgTemp.getHeight(null) + StringConstants.BLANK;				
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
			picture.setEpicFileWidth(w);
			picture.setEpicFileHeight(h);
			baseService.saveOrUpdate(picture);
		}
			
		HreUser tmpUser = new HreUser();
		tmpUser.setUserName(employeeDAOService.getNewUsername(
				CommonUtils.normalizeString(beanForm.getEmpFirstname()),
				CommonUtils.normalizeString(beanForm.getEmpMiddleName()),
				CommonUtils.normalizeString(beanForm.getEmpLastname())));

		if (tmpUser.getUserName() != null) {

			tmpUser.setUserPassword(Encrypter.encodeMD5(beanForm.getPassword()));
			tmpUser.setUserRoleId(beanForm.getUserRoleId());
			tmpUser.setEmpNumber(tmp.getEmpNumber());
			tmpUser.setDeleted(false);
			tmpUser.setStatus(beanForm.isStatus());
			tmp.setDateModified(new Date());
	
			baseService.saveOrUpdate(tmpUser);
	
			tmp.setMainUsername(tmpUser.getUserName());
			baseService.saveOrUpdate(tmp);
		}

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}
	
	private void initFormBean(EmployeeAddForm beanForm) {

		beanForm.setAllStatuses(ComboBoxInit.getAllEnabledStatuses(false));
		beanForm.setAllUserRoles(ComboBoxInit.getAllUserRoles(true, false));
	}
	
	private String validateForm (EmployeeAddForm beanForm) {
		
		if(StringUtils.isBlank(CommonUtils.normalizeString(beanForm.getEmpFirstname()))){
			return "First name cannot be blank!";
		}

		if(StringUtils.isBlank(CommonUtils.normalizeString(beanForm.getEmpLastname()))){
			return "Last name cannot be blank!";
		} 
		
		FormFile myFile = beanForm.getImage();
		if(myFile != null && StringUtils.isNotBlank(myFile.getFileName())){
			if(myFile.getFileSize() > 2097152){
				return "Image file size is too big! (< 2MB required)";
			} else if(!"image/jpeg".equalsIgnoreCase(myFile.getContentType())){
				return "Invalid file type! Only JPEG or PNG files are accepted!";
			}
		}

		if (StringUtils.isBlank(beanForm.getPassword())) {
			return "Password cannot be blank!";
		}

		if(!beanForm.getPassword().equals(beanForm.getConfirmPassword())){
			return "Confirm password does not match!";
		}

		String verifyPassword = CommonUtils.verifyPassword(beanForm.getPassword());
		if (!StringConstants.BLANK.equals(verifyPassword)) {
			return verifyPassword;
		}

		return StringConstants.BLANK;
	}
}
